package com.bnlr.lrparking.appui.sharevalue.recharge;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.approve.ApproveActivity;
import com.bnlr.lrparking.appui.paypwd.SetPayPasswordActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.ToUpAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.appui.bank.model.BankCardM;
import com.bnlr.lrparking.model.TopUpM;
import com.bnlr.lrparking.model.WxM;
import com.bnlr.lrparking.util.pwddialog.SecurityEditCompileListener;
import com.bnlr.lrparking.util.pwddialog.SecurityPasswordEditText;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hp on 2017/8/25.
 * 充值界面
 *
 * @author hasee
 */
public class TopUpActivity extends BaseActivity {

    private TextView tvNavTitle,textView4,tvChangeRate;
    private ToUpAdapter adapter;
    private GridView gridr_view;
    private EditText ed_toup_num;
    private List<TopUpM.DataBean> list=new ArrayList<>();
    private RelativeLayout rely_wx,rely_sy,rely_ednum;
    private CheckedTextView checkBox_wx,checkBox_sy;
    /**
     * 0是微信支付
     * 1是收益值支付
     */
    private int payType=0;
    private TextView tv_topup_btn;
    private AlertDialog paydialog;
    /**
     * 支付密码
     */
    String idHavapaypassword;
    private String LatShareValue="";
    private boolean isClick = false;
    SecurityPasswordEditText editSecurityCode;
    private String hasRealAuth;
    private String EdNum="0";
    private int intclick=-1;
    /**
     * false
     */
    private boolean isClickEd=false;
    private int intNum[]={LrConstant.RATE_VALUE*10,LrConstant.RATE_VALUE*50,LrConstant.RATE_VALUE*100,LrConstant.RATE_VALUE*200,LrConstant.RATE_VALUE*500,LrConstant.RATE_VALUE*1000};
    DecimalFormat df =new DecimalFormat("#0.00");
    String residue = "0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topup);
        residue = getIntent().getStringExtra("shouyi");
        initView();
    }

    private void initView(){

        tvNavTitle = (TextView) findViewById(R.id.tv_nav_title);
        tvNavTitle.setText("充值中心");
        rely_wx=(RelativeLayout) findViewById(R.id.rely_wx);
        rely_sy=(RelativeLayout) findViewById(R.id.rely_sy);
        rely_ednum=(RelativeLayout)findViewById(R.id.rely_ednum);
        ed_toup_num=(EditText)findViewById(R.id.ed_toup_num);
        checkBox_wx=(CheckedTextView)findViewById(R.id.checkBox_wx);
        checkBox_sy=(CheckedTextView)findViewById(R.id.checkBox_sy);
        tv_topup_btn=(TextView)findViewById(R.id.tv_topup_btn);
        textView4 = (TextView) findViewById(R.id.textView4);
        tvChangeRate = (TextView) findViewById(R.id.tv_exchange_rate);
        tvChangeRate.setText("1、"+LrConstant.RATE_VALUE+"贡献值=人民币1元");
        rely_wx.setOnClickListener(this);
        rely_sy.setOnClickListener(this);
        tv_topup_btn.setOnClickListener(this);
        textView4.setText("(剩余"+residue+"收益值)");
        gridr_view=(GridView)findViewById(R.id.gridr_view);
        getTopUpValue();
        adapter=new ToUpAdapter(TopUpActivity.this,list);
        gridr_view.setAdapter(adapter);
        gridr_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isClickEd=false;
                intclick=position;
                if (payType==0) {
                    tv_topup_btn.setText("立即支付    " + list.get(position).getRMBNumber() + "元");
                }else {
                    tv_topup_btn.setText("立即支付    " + list.get(position).getShareValue()+ "收益值");
                }
                adapter.setSelectPosition(position);
                adapter.notifyDataSetChanged();
                LatShareValue= String.valueOf(list.get(position).getShareValue());
                isClick = true;
                ed_toup_num.setText("");
                ed_toup_num.clearFocus();
            }
        });
        ed_toup_num.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // 获得焦点
                if(hasFocus){
                    LatShareValue = "";
                    ed_toup_num.addTextChangedListener(TopUpActivity.this);
                    isClickEd=true;
                    tv_topup_btn.setText("立即支付");
                    rely_ednum.setBackgroundResource(R.drawable.topup_click_line_bg);
                    adapter.setSelectPosition(-1);
                    adapter.notifyDataSetChanged();
                }else{//失去焦点
                    rely_ednum.setBackgroundResource(R.drawable.topup_line_bg);
                }
            }
        });
    }

    /**
     * 获取充值模板
     */
    private void getTopUpValue() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "GetChongZhiTemplate");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<TopUpM>(baseContext, true, TopUpM.class) {
                        @Override
                        public void doWork(TopUpM data, String code) {
                            if (code.equals("1")) {
                               list.clear();
                               list.addAll(data.getData());
                               adapter.notifyDataSetChanged();

                            }else {
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }


    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        EdNum= ed_toup_num.getText().toString();
        if (s.length() > 0){
            adapter.setSelectPosition(-1);
            adapter.notifyDataSetChanged();
            if (isClick) {
                isClick = false;
            }
        }
        if (!isClick) {
            LatShareValue = s.toString();
        }
        if (isClickEd==true) {
            if (payType == 0) {
                if (EdNum.length() > 0) {
                    if ((Double.valueOf(EdNum) * 100 % LrConstant.RATE_VALUE == 0)){
                        tv_topup_btn.setText("立即支付    " +df.format((Double.valueOf(EdNum)*100 / LrConstant.RATE_VALUE)/100) + "元");
                    }
                    else
                    {
                        tv_topup_btn.setText("立即支付    " +df.format(((Double.valueOf(EdNum)*100 / LrConstant.RATE_VALUE)+1)/100) + "元");
                    }

                } else if (EdNum.length() == 0) {
                    tv_topup_btn.setText("立即支付");
                }
            } else {
                if (EdNum.length() > 0) {
                    tv_topup_btn.setText("立即支付    " + EdNum + "收益值");
                } else if (EdNum.length() == 0) {
                    tv_topup_btn.setText("立即支付");
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        idHavapaypassword = AppConfig.getInstance().getString("paypassword", "");
        hasRealAuth = AppConfig.getInstance().getString("isRealNameAuth","");
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.rely_wx:
                payType=0;
                checkBox_wx.setChecked(false);
                checkBox_sy.setChecked(true);
                if (!isClickEd) {
                    if (intclick == -1) {
                        return;
                    }
                    tv_topup_btn.setText("立即支付    " + df.format(intNum[intclick] / LrConstant.RATE_VALUE) + "元");
                }else {
                    if (EdNum.length()>0) {
                        tv_topup_btn.setText("立即支付    " + df.format(Double.valueOf(EdNum) / LrConstant.RATE_VALUE) + "元");
                    }else {
                        tv_topup_btn.setText("立即支付");
                    }
                }
                break;
            case R.id.rely_sy:
                payType=1;
                checkBox_wx.setChecked(true);
                checkBox_sy.setChecked(false);
                if (!isClickEd) {
                    if (intclick == -1) {
                        return;
                    }
                    tv_topup_btn.setText("立即支付    " + intNum[intclick] + "收益值");
                }else {
                    if (EdNum.length()>0) {
                        tv_topup_btn.setText("立即支付    " + EdNum + "收益值");
                    }else {
                        tv_topup_btn.setText("立即支付");
                    }
                }
                break;
            case R.id.tv_topup_btn:
//                if(!isAuth()) {
//                    return;
//                }
                if (payType == 1) {
                    if (idHavapaypassword.equals("1")) {
                        if (!TextUtils.isEmpty(LatShareValue)) {
                            showPayDialog();
                        }else {
                            ToastUtils.showShort("请选择充值金额");
                        }
                    } else {
                        SetPayPassword();
                    }
                } else {
                    if (!TextUtils.isEmpty(LatShareValue)) {
                        getWX(LatShareValue,"1",LrConstant.WX_APP_ID);
                    }else {
                        ToastUtils.showShort("请选择充值金额");
                    }
                }

                break;
            default:
                break;
        }
    }

    /**
     * 获取微信
     */
    private void getWX(final String shareValue, String type, String appId){
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "ChongZhi");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("shareValue", shareValue);
            mRequest.add("type",type);
            mRequest.add("appId",appId);

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<WxM>(baseContext, true, WxM.class) {
                        @Override
                        public void doWork(WxM data, String code) {
                            if (code.equals("1")) {
                                AppConfig.getInstance().putString("wx_order_id", data.getData().getOrderNo());
                                AppConfig.getInstance().putString("wx_top_up", shareValue);
                                doWXPay(data.getData());
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }


    /**
     * 判断是否实名认证
     *
     * @return
     */
    public boolean isAuth () {
        CarCommon carCommon = new CarCommon();
        if (hasRealAuth.equals("0")) {
            carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                @Override
                public void setSure() {
                    startActivity(ApproveActivity.class);
                }
            });
            carCommon.CommonDialog(TopUpActivity.this,"请您先去进行实名认证",null);
            return false;
        }else if (hasRealAuth.equals("2")){
            carCommon.ReminderDialog(TopUpActivity.this,"身份信息正在审核中，请稍候再试",null);
            return false;
        } else if (hasRealAuth.equals("3")) {
            carCommon.ReminderDialog(TopUpActivity.this,"您的实名认证未通过，请重新在个人中心认证",null);
            return false;
        } else {
            return true;
        }
    }
    private void getTransIncomeToShare(String count,String payPassword){
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "TransIncomeToShare");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("count", count);
            mRequest.add("payPassword",payPassword);

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BankCardM>(baseContext, true, BankCardM.class) {
                            @Override
                            public void doWork(BankCardM data, String code) {
                                if (code.equals("1")) {
                                }else {
                                }
                            }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (code.equals("1")) {
                                    ToastUtils.showShort("充值成功");
                                    finish();
                                }else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                    editSecurityCode.clearEdit();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    /**
     * 支付弹框
     */
    public void showPayDialog() {
        paydialog = new AlertDialog.Builder(this).create();
        paydialog.setCanceledOnTouchOutside(false);
        paydialog.setView(new EditText(this));
        paydialog.show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(editSecurityCode!=null){
                    //设置可获得焦点
                    editSecurityCode.getEditText().setFocusable(true);
                    editSecurityCode.getEditText().setFocusableInTouchMode(true);
                    //请求获得焦点
                    editSecurityCode.getEditText().requestFocus();
                    //调用系统输入法
                    InputMethodManager inputManager = (InputMethodManager) editSecurityCode.getEditText()
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editSecurityCode.getEditText(), 0);
                }
            }
        }, 200);

        Window window = paydialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        paydialog.setContentView(R.layout.activity_input_password_dialog);

        final RelativeLayout pay_back=(RelativeLayout)window.findViewById(R.id.pay_back);
        pay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paydialog.dismiss();
            }
        });
        editSecurityCode = (SecurityPasswordEditText) window
                .findViewById(R.id.security_linear);
        editSecurityCode.setSecurityEditCompileListener(new SecurityEditCompileListener() {
            @Override
            public void onNumCompleted(String num) {
                getTransIncomeToShare(LatShareValue,num);
            }
        });
    }

    /**
     * 这个是判断是不是已经设置支付密码
     */
    private void SetPayPassword(){
            final NormalDialog dialog = new NormalDialog(baseContext);
            dialog.title("安全提示")
                    .titleTextColor(baseContext.getResources().getColor(R.color.black_color))
                    .titleTextSize(15)
                    .content("您还没有支付密码，请先设置！")
                    .contentTextSize(15)
                    .contentTextColor(baseContext.getResources().getColor(R.color.gray_color))
                    .btnText("取消", "设置")
                    .btnNum(2)
                    .style(NormalDialog.STYLE_TWO)
                    .btnTextColor(baseContext.getResources().getColor(R.color.gray_color), baseContext.getResources().getColor(R.color.colorAccent))
                    .btnTextSize(15, 15)
                    .widthScale(0.8f)
                    .showAnim(new BounceTopEnter())
                    .dismissAnim(new SlideBottomExit())
                    .cornerRadius(7)
                    .show();
            dialog.setCancelable(true);
            dialog.setOnBtnClickL(
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                        }
                    },
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                            startActivity(SetPayPasswordActivity.class);
                        }
                    });
    }
    /**
     * 微信支付
     * @param data
     */
    private void doWXPay(WxM.Data data) {

        boolean isPaySupported =  Application.mWxApi.isWXAppInstalled();
        if(!isPaySupported){
            ToastUtils.showShort("手机不支持微信支付");
            return;
        }

        PayReq request = new PayReq();
        request.appId = LrConstant.WX_APP_ID;
        request.partnerId = data.getPartnerid();
        request.prepayId= data.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr= data.getNoncestr();
        request.timeStamp= data.getTimestamp();
        request.sign= data.getSign();
        request.extData = "app data";

        LogUtils.i("PayReq", request.toString());
        LogUtils.i("data", data.toString());

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showShort("微信支付获取中....");
            }
        });

        Application.mWxApi.sendReq(request);
    }
}
